package com.webchat.dao;

import com.webchat.Utils.HibernateUtil;
import com.webchat.model.UsersFriendshipsEntity;

import javax.persistence.EntityManager;
import java.util.List;

public class UsersFriendDao {

    public boolean isFriend(Integer uid, Integer friendid){

        List<UsersFriendshipsEntity> result = this.getFriendList(uid);
        for ( UsersFriendshipsEntity ufe : result) {
            if (
                (ufe.getUid() == uid && ufe.getFriendUid() == friendid)
                    ||
                (ufe.getUid() == friendid && ufe.getFriendUid() == uid)
            ){
                return true;
            }
        }
        return  false;
    }

    public List<UsersFriendshipsEntity> getFriendList(Integer uid){
        EntityManager manager = HibernateUtil.getSessionFactory().createEntityManager();
        manager.getTransaction().begin();
        String sql = "from UsersFriendshipsEntity WHERE uid = "+uid+" or friendUid = "+uid;
        List<UsersFriendshipsEntity> list =
                manager.createQuery(sql, UsersFriendshipsEntity.class).getResultList();
        manager.getTransaction().commit();
        manager.close();
        return list;
    }
}
